package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.entity.FileRecord;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.FileRecordService;
import org.csu.onlineedubackend.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.entity.User;
import jakarta.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@CrossOrigin(origins = "http://localhost:5173") // 允许跨域
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private FileRecordService fileRecordService;

    @Autowired
    private LogService logService;

    @Autowired
    private UserService userService;

    // 上传单个音频文件
    @PostMapping("/upload/audio")
    public CommonResponse<Map<String, String>> uploadAudio(@RequestParam("file") MultipartFile file,
                                                           @RequestParam("userId") Integer userId) {
        if (file.isEmpty()) {
            return CommonResponse.createForError(400, "没有有效的文件被上传");
        }

        try {
            String fileUrl = fileUtil.uploadFile(file);

            FileRecord record = new FileRecord();
            record.setUserId(userId);
            record.setOriginalFilename(file.getOriginalFilename());
            record.setFileUrl(fileUrl);
            record.setSize(file.getSize());

            fileRecordService.save(record);

            Map<String, String> result = new HashMap<>();
            result.put("fileUrl", fileUrl);

            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "文件上传成功", result);
        } catch (Exception e) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "文件上传失败: " + e.getMessage());
        }
    }

    // 上传文件并记录到数据库
    @PostMapping("/upload")
    public CommonResponse<List<FileRecord>> uploadFiles(@RequestParam("file") MultipartFile[] files,
                                                        @RequestParam("userId") Integer userId,
                                                        HttpServletRequest request) {
        List<FileRecord> records = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    String fileUrl = fileUtil.uploadFile(file);
                    String storedFileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                    FileRecord record = new FileRecord();
                    record.setUserId(userId);
                    record.setOriginalFilename(file.getOriginalFilename());
                    record.setFileUrl(fileUrl);
                    record.setSize(file.getSize());
                    fileRecordService.save(record);
                    records.add(record);
                    // 日志记录
                    User user = userService.getById(userId);
                    String username = user != null ? user.getUsername() : null;
                    String ip = request.getRemoteAddr();
                    String userAgent = request.getHeader("User-Agent");
                    logService.recordTeacherCourseOperation(userId, username, null, null, "UPLOAD_FILE", "上传文件: " + file.getOriginalFilename(), ip, userAgent);
                }
            }
            if (records.isEmpty()) {
                return CommonResponse.createForError(400, "没有有效的文件被上传");
            }
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "文件上传成功", records);
        } catch (Exception e) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "文件上传失败: " + e.getMessage());
        }
    }

    // 查询用户上传的所有文件
    @GetMapping("/list/{userId}")
    public CommonResponse<List<FileRecord>> listFilesByUser(@PathVariable Integer userId) {
        List<FileRecord> list = fileRecordService.getFilesByUser(userId);
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", list);
    }

    // 根据文件名查询文件信息
    @GetMapping("/info")
    public CommonResponse<FileRecord> getFileInfoByFileName(@RequestParam("fileName") String fileName) {
        try {
            FileRecord fileRecord = fileRecordService.getFileByFileName(fileName);
            if (fileRecord != null) {
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", fileRecord);
            } else {
                return CommonResponse.createForError(404, "文件不存在");
            }
        } catch (Exception e) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "查询失败: " + e.getMessage());
        }
    }
}
